﻿using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Net;
using Microsoft.AspNetCore.Builder;

namespace Naruto.TaskManagement.Infrastructure
{
    /// <summary>
    /// 异常处理的中间件
    /// </summary>
    public class ExceptionHandlerMiddleware
    {
        /// <summary>
        /// 定义一个请求委托
        /// </summary>
        private readonly RequestDelegate next;


        public ExceptionHandlerMiddleware(RequestDelegate request)
        {
            next = request;
        }
        /// <summary>
        /// 中间件的处理
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            try
            {
                await next(context);
            }
            catch (Exception ex)
            {
                //获取底层的异常
                ex = ex.GetBaseException();
                await HandleExceptionAsync(context, new NarutoFailResult(ex.Message));
            }
        }
        /// <summary>
        /// 事件的处理与数据的返回
        /// </summary>
        /// <param name="context"></param>
        /// <param name="jsonResult"></param>
        /// <returns></returns>

        private static async Task HandleExceptionAsync(HttpContext context, NarutoResult jsonResult)
        {
            context.Response.ContentType = "application/json;charset=utf-8";
            await context.Response.WriteAsync(jsonResult.ToJson()).ConfigureAwait(false);
        }
    }

    public static class ExceptionHandlerMiddlewarExtension
    {
        public static void UseExceptionHandle(this IApplicationBuilder builder)
        {
            builder.UseMiddleware<ExceptionHandlerMiddleware>();
        }
    }
}
